﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    [Route("pl")]
    public class PLController : PageController
    {
        public SQLCommand sqlcmd = new SQLCommand();
        /// <summary>
        /// 主管流水线信息
        /// </summary>
        [HttpGet]
        public HttpResponseMessage GetPL()
        {
            
            SQLCommand sc = null;
            try
            {
                // 一主管只有一条流水线  一条流水线只有一个主管  管理员可看所有流水线 
                User user = GetUserByLoginID(GetCrrentIDByToken());
                DataTable dt = null;
                string sql = "";
                if (user == null)
                    return AssistFun.toJson(new { status = 201, tip = "用户信息有误", data = "" });
                if (user.power == 2)
                {
                    sql = "select id,PL_tb.name,type,autocreate,PL_tb.state from PL_tb where PL_tb.state=1";
                    sc = new SQLCommand(sql);
                    dt = sc.ExecuteScalars();
                    dt.Columns.Add("UserName", typeof(string));
                    dt.Columns.Add("login_id", typeof(Int32));
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        List<string> ss = GetUserNameByPLId(Convert.ToInt32(dt.Rows[i]["id"]));
                        if (ss.Count > 0)
                        {
                            dt.Rows[i]["UserName"] = ss[0];
                            dt.Rows[i]["login_id"] = ss[1];
                        }
                    }
                }
                else
                {
                    sql = "select id,PL_tb.name,type,autocreate,PL_tb.state,User_tb.name as UserName from PL_tb join User_tb on PL_tb.id=User_tb.PLID where PL_tb.state=1 and User_tb.login_id=" + user.login_id;
                    sc = new SQLCommand(sql);
                    dt = sc.ExecuteScalars();
                }
                if (dt != null)
                    return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = dt.Rows.Count, rows = AssistFun.DataTableToList<PLShow>(dt) } });
                else
                    return AssistFun.toJson(new { status = 201, tip = "暂时没有流水线数据", data = "" });
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
            }
        }

        /// <summary>
        /// 随机获取一条流水线上的其中一个主管的姓名
        /// </summary>
        /// <param name="plid"></param>
        /// <returns></returns>
        private List<string> GetUserNameByPLId(int plid)
        {
            string sql = "select name,login_id from User_tb where power=1 and PLID=@plid and name!=''";
          
            SQLCommand sc = new SQLCommand(sql, "@plid", plid);
            DataTable names = sc.ExecuteScalars();
            List<string> result = new List<string>();            
            if (names != null)
            {
                foreach (DataRow item in names.Rows)
                {
                    result.Add(item["name"].ToString());
                    result.Add(item["login_id"].ToString());
                    break;
                }
            }
            return result;
        }
        // POST: api/PL
        /// <summary>
        /// 新增流水线  数据库使用整形表示  故0表示团订 1表示成衣
        /// </summary>
        /// <param name="obj">login_id该流水线所属主管的工号，type流水线类型，name流水线名称</param> 
        [HttpPost]
        public HttpResponseMessage Post(dynamic obj)
        {
            //判断表中是否有该流水线
            string name = obj.name.ToString(); //流水线名称
            int type = Convert.ToInt32(obj.type); //流水线类型            
            int loginid = Convert.ToInt32(obj.login_id); //流水线所属工号
            int currentLoginid = GetCrrentIDByToken();
            SQLCommand sc = new SQLCommand("select name from PL_tb where name=@name","@name", name);
            if (sc.ExecuteScalar() != null)
                return AssistFun.toJson(new RespondModel(201, "已经存在" + name));
            else
            {
                List<SQLCommand> sqlstr = new List<SQLCommand>();
                AddCmdForPL(name, type, loginid, currentLoginid, ref sqlstr);
                try
                {
                    if (SQLCommand.ExecTran(sqlstr) == 1)
                        return AssistFun.toJson(new RespondModel(200, "成功"));
                    else
                        return AssistFun.toJson(new RespondModel(201, "流水线添加失败"));
                }
                catch (Exception e)
                {
                    return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
                }
            }
        }

        [HttpPut, Route("pl/setplforuser")]
        public HttpResponseMessage UpdatePLForUser(dynamic obj)
        {
            int loginid = Convert.ToInt32(obj.loginid);
            int plid = Convert.ToInt32(obj.plid);

            SQLCommand sc = null;
            //流水线id plid  工号
            string sql = "select * from User_tb where login_id=@loginid and state<>5";
            sc = new SQLCommand(sql, "@loginid", loginid);
            DataRow dr = sc.ExecuteOneRow();
            User user = null;
            List<SQLCommand> cmds = new List<SQLCommand>();
            if (dr != null)
            {
                user = AssistFun.DataRowToObject<User>(dr);
                if (user.power == 1 && user.PLID != 0)
                    return AssistFun.toJson(new { status = 201, tip = "工号" + loginid + "已经是主管，且管理了流水线" });
                else
                    AddCmdForUser(loginid, plid, ref cmds);
            }
            else
            {
                AddCmdForUser(loginid, plid, ref cmds);
            }
            if (SQLCommand.ExecTran(cmds) != 1)
                return AssistFun.toJson(new { status = 201, tip = "操作失败" });
            return AssistFun.toJson(new { status = 200, tip = "成功" });

        }
        /// <summary>
    /// 修改流水线（新增或忽略工序）
    /// </summary>
    /// <param name="obj">delcode被忽略的工序编码 setcode需要修改upload标记的工序编码  PLID流水线id  name需要新增的那个工序的名称</param>
        [HttpPut]
        public HttpResponseMessage UpdatePL(dynamic obj)
    {
        string sql = "";
        int plid = Convert.ToInt32(obj.id);
        int delcode = Convert.ToInt32(obj.delcode);
        int setcode = Convert.ToInt32(obj.setcode);
        SQLCommand sc = null;
        List<SQLCommand> cmds = new List<SQLCommand>();
        //删除流水线下的工序 
        if (delcode != 0)
        {
            sql = "delete from Process_tb where code=@code and PLID=@plid";
            sc = new SQLCommand(sql);
            sc.Add("@plid", plid);
            sc.Add("@code", delcode);
            cmds.Add(sc);
        }
        else
        {
            //新增工序  但不忽略工序  所以要将之前工序的upload改为0
            sc = new SQLCommand("select code from Process_tb where PLID=@plid and upload=1", "@plid", plid);
            int code = Convert.ToInt32(sc.ExecuteScalar());
            if (code < setcode)
            {
                sql = "update Process_tb set upload=0 where code=@code and PLID=@plid";
                sc = new SQLCommand(sql);
                sc.Add("@plid", plid);
                sc.Add("@code", delcode);
                cmds.Add(sc);
            }
        }
        try
        {
            sc = new SQLCommand("select doerCode from Process_tb where code = @code and PLID = @plid");
            sc.Add("@plid", plid);
            sc.Add("@code", setcode);
            string doerCode = sc.ExecuteScalar();
            if (doerCode != null)
            {
                //修改流水线工序的upload值 
                sql = "update Process_tb set upload=1 where code=@code and PLID=@plid";
            }
            else
            {
                //没有该工序  新增工序 
                sql = string.Format("insert into Process_tb values(@code,'{0}',@plid,1,{1},0)", obj.name.ToString(),0);
            }
            sc = new SQLCommand(sql);
            sc.Add("@plid", plid);
            sc.Add("@code", setcode);
            cmds.Add(sc);
            if (SQLCommand.ExecTran(cmds) == 0)
            {
                return AssistFun.toJson(new { status = 201, tip = "未能处理工序", data = "" });
            }
            else
            {
                return AssistFun.toJson(new { status = 200, tip = "成功处理", data = "" });
            }
        }
        catch (Exception e)
        {
            return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
            throw;
        }
    }
        //修改工序权重
        [HttpPost,Route("UpdateWeight")]
        public HttpResponseMessage UpdateWeight(dynamic obj)
        {
            int plid = Convert.ToInt32(obj.PLID);
            int code= Convert.ToInt32(obj.code);
            double weight = Convert.ToDouble(obj.weight);
            string sql = "update Process_tb set weight="+weight+" where code="+code+" and PLID="+plid;
            SQLCommand sc = new SQLCommand(sql);
            int num=sc.ExecuteNonQuery();
            if (num > 0)
            {
                return AssistFun.toJson(new RespondModel(200, "修改成功"));
            }
            else
            {
                return AssistFun.toJson(new RespondModel(201, "修改失败"));
            }
        }
        //修改流水线名称
        [HttpPost,Route("UpdatePlName")]
        public HttpResponseMessage UpdatePlName(dynamic obj)
        {
            int PLID = Convert.ToInt32(obj.PLID);
            string PLName =Convert.ToString(obj.PLName);
            string sql = "update PL_tb set name=@PLName where id=@PLID";
            SQLCommand sc = new SQLCommand(sql);
            sc.Add("@PLName",PLName);
            sc.Add("@PLID",PLID);
            int num = sc.ExecuteNonQuery();
            if (num > 0)
            {
                return AssistFun.toJson(new RespondModel(200, "修改成功"));
            }
            else
            {
                return AssistFun.toJson(new RespondModel(201, "修改失败"));
            }
        }

    #region  添加流水线的相关操作
    private void AddCmdForPL(string name, int type, int loginid, int currentLoginid, ref List<SQLCommand> strSql)
    {
        //获取新增流水线的ID
        int plid = GetNewSafeID(currentLoginid);

        SQLCommand sc = new SQLCommand("insert into PL_tb(id,name,type) values(@id,@name,@type)");
        sc.Add("@id", plid);
        sc.Add("@name", name);
        sc.Add("@type", type);

        strSql.Add(sc);

        AddCmdForUser(loginid, plid, ref strSql);

        AddCmdForProcess(type, plid, ref strSql);
    }

    /// <summary>
    /// 定义新增员工的sql语句以及参数
    /// </summary>
    /// <param name="loginid"></param>
    /// <param name="plid"></param>
    /// <param name="strSql"></param>
    /// <param name="paraList"></param>
    private void AddCmdForUser(int loginid, int plid, ref List<SQLCommand> strSql)
    {

        //获取登入用户
        SQLCommand sc = new SQLCommand("select login_id from User_tb where login_id=@loginid", "@loginid", loginid);
        //该工号不存在 
        if (sc.ExecuteScalar() == null)
        {
            sc = new SQLCommand("insert into User_tb(PLID,login_id,power) values(@plid,@loginid,@power)");
            sc.Add("@loginid", loginid);
            sc.Add("@power", 1);
            sc.Add("@plid", plid);
            strSql.Add(sc);
        }
        else
        {
            sc = new SQLCommand("update User_tb set PLID=@plid,power=1 where login_id=@loginid");
            sc.Add("@loginid", loginid);
            sc.Add("@plid", plid);
            strSql.Add(sc);
        }
    }

    /// <summary>
    /// 定义新增工序的sql语句以及参数
    /// </summary>
    /// <param name="plid"></param>
    /// <param name="pltype"></param>
    /// <returns></returns>
    private void AddCmdForProcess(int pltype, int plid, ref List<SQLCommand> strSql)
    {
        List<Item> process = new List<Item>();
        SQLCommand sc = null;
        if (pltype == 0) //团订  
        {
            process = GetTDProcess();
            for (int i = 0; i < process.Count; i++)
            {
                if (process[i].code == 27)
                {
                    sc = new SQLCommand("insert into Process_tb(PLID,code,name,upload,doerCode) values(@plid,@code,@name,@upload,@doerCode)");
                    sc.Add("@plid", plid);
                    sc.Add("@code", process[i].code);
                    sc.Add("@name", process[i].name);
                    sc.Add("@upload", 1);
                    sc.Add("@doerCode", process[i].code);
                    strSql.Add(sc);

                }
                else
                {
                    sc = new SQLCommand("insert into Process_tb(PLID,code,name,doerCode) values(@plid,@code,@name,@doerCode)");
                    sc.Add("@plid", plid);
                    sc.Add("@code", process[i].code);
                    sc.Add("@name", process[i].name);
                    sc.Add("@doerCode", process[i].code);

                    strSql.Add(sc);
                }
            }
        }
        else
        {
            process = GetCYProcess();
            for (int i = 0; i < process.Count; i++)
            {
                if (process[i].code == 18)
                {
                    sc = new SQLCommand("insert into Process_tb(PLID,code,name,upload,doerCode) values(@plid,@code,@name,@upload,@doerCode)");
                    sc.Add("@plid", plid);
                    sc.Add("@code", process[i].code);
                    sc.Add("@name", process[i].name);
                    sc.Add("@upload", 1);
                    sc.Add("@doerCode", process[i].code);
                    strSql.Add(sc);
                }
                else
                {
                    sc = new SQLCommand("insert into Process_tb(PLID,code,name,doerCode) values(@plid,@code,@name,@doerCode)");
                    sc.Add("@plid", plid);
                    sc.Add("@code", process[i].code);
                    sc.Add("@name", process[i].name);
                    sc.Add("@doerCode", process[i].code);

                    strSql.Add(sc);
                }
            }
        }

    }
    #endregion

    #region  暂时注释的修改流水线工序  
    /// <summary>
    /// 修改流水线 忽略流水线的工序(删除工序表中被忽略的工序),与此同时修改最后一个改版工序的upload值
    /// </summary> 成衣:13-16  团订 22-27 
    /// <param name="pro">操作类型type(工序 约束) 工序:操作类型（忽略，新增），code 约束:操作类型（忽略，新增），code,assign（修改约束时要判断相应工序  若是工序已被忽略则不存在约束修改）</param>
    /// 综合4个参数  type int ,action int ,code,assign   0表示操作工序-type  0表示忽略工序，没有约束 action
    //public void Put(Item pro,int action,int optype)
    //{
    //    //1.判断该流水线的类型(成衣/团订) 2.获取该流水线类型的  最后一个改版工序的upload值 uploadcode 3.判断last值再判断传递的code值然后进行相应修改
    //    int type =int.Parse(SQLHelpExtension.ExecuteScalar(new SQLCommand("select type from Process_tb where id=@plid",new SqlParameter("@plid",pro.PLID))));
    //    int uploadcode = int.Parse(SQLHelpExtension.ExecuteScalar(new SQLCommand("select code from Process_tb where upload=1 and PLID=@plid", new SqlParameter("@plid", pro.PLID))));
    //    if (type == 0) //团订
    //    {
    //        TDUpdateInfo(pro.code,action,uploadcode,pro.PLID,pro.name);
    //    }
    //    else //成衣 
    //    {
    //        CYUpdateInfo(pro.code, action, uploadcode, pro.PLID, pro.name);
    //    }            
    //}
    //private void CYUpdateInfo(int code, int action, int uploadcode, int plid, string name)
    //{
    //    UpdateProcess(action, code, uploadcode, plid,name,15);
    //}

    ///// <summary>
    ///// 
    ///// </summary>
    ///// <param name="code">工序编码</param>
    ///// <param name="action">操作类型</param>
    ///// <param name="uploadcode">文件上传的工序编码</param>
    ///// <param name="plid">流水线id</param> 
    ///// <param name="name">工序名称</param>
    //private void TDUpdateInfo(int code,int action,int uploadcode,int plid,string name)
    //{
    //    //if (code >= 22 && code <= 27)
    //    //{
    //        UpdateProcess(action,code,uploadcode,plid,name,22);
    //    //}
    //}

    //private void UpdateProcess(int action,int code,int uploadcode,int plid,string name,int begincode)
    //{
    //    if (action == 0) //忽略
    //    {
    //        if (code < uploadcode)
    //        {
    //            SQLCommand delcmd = new SQLCommand("delete from Process_tb where code=@code and PLID=@plid", null);
    //        }
    //        else if (code > uploadcode)
    //        {
    //            SQLCommand delcmd = new SQLCommand("delete from Process_tb where code=@code and PLID=@plid", new SqlParameter("@code", uploadcode));
    //            SQLCommand updcmd = new SQLCommand("update Process_tb set upload=1 where code=@code and PLID=@plid", new SqlParameter("@code", code));
    //        }
    //        else //相等
    //        {
    //            string sql = string.Format("select top 1 code from Process_tb where code>= {2} and code<{0} and PLID={1} order by code desc", code, plid,begincode);
    //            //获取没有被忽略的最大工序code
    //            string maxcode = SQLHelpExtension.ExecuteScalar(new SQLCommand(sql, null));
    //            if (maxcode == null)
    //            {
    //                //拒绝修改
    //            }
    //            else
    //            {
    //                SQLCommand delcmd = new SQLCommand("delete from Process_tb where code=@code and PLID=@plid", new SqlParameter("@code", code));
    //                SQLCommand updcmd = new SQLCommand("update Process_tb set upload=1 where code=@code and PLID=@plid", new SqlParameter("@code", maxcode));
    //            }
    //        }
    //    }
    //    else  //添加
    //    {
    //        if (code < uploadcode)
    //        {
    //            SQLCommand addcmd = new SQLCommand("insert into Process_tb(code,PLID,name)values(@code,@plid,@name)", null);
    //        }
    //        else if (code > uploadcode)
    //        {
    //            SQLCommand delcmd = new SQLCommand("insert into Process_tb(code,PLID,name,upload)values(@code,@plid,@name,1)", new SqlParameter("@code", code));
    //            SQLCommand updcmd = new SQLCommand("update Process_tb set upload=1 where code=@code and PLID=@plid", new SqlParameter("@code", uploadcode));
    //        }
    //    }
    //}
    #endregion
}

}
